package com.qf.openapi.web.master.interceptor;

import com.qf.openapi.web.master.entity.User;
import com.qf.openapi.web.master.service.UserSevice;
import com.qf.openapi.web.master.utils.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
public class AutoLoginInterceptor implements HandlerInterceptor {

    private UserSevice userSevice;

    public UserSevice getUserSevice() {
        return userSevice;
    }

    public void setUserSevice(UserSevice userSevice) {
        this.userSevice = userSevice;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1. 判断，如果session中有user对象了，那么直接重定向到 /plateform.html
        final HttpSession session = request.getSession();
        final User sessionUser = (User) session.getAttribute(Constants.SESSION_USER_KEY);

        if (sessionUser!=null){
            log.debug("用户已经登录过了，直接重定向到首页");
            response.sendRedirect("/plateform.html");
            return false;
        }

        //2. 检查请求中是否有usertoken cookie，有的话还原用户的登录状态
        final Cookie[] cookies = request.getCookies();

        if (cookies!=null && cookies.length>0) {

            for (Cookie cookie : cookies) {
                final String name = cookie.getName();
                if (name.equals(Constants.USER_TOKEN)){
                    final String usertokenvalue = cookie.getValue();
                    final String[] split = usertokenvalue.split("-");
                    final String username = split[0];
                    final String md5password = split[1];

                    // 还原用户登录状态
                    User user = userSevice.restoreUser(username,md5password);

                    // 把user对象放入session中
                    session.setAttribute(Constants.SESSION_USER_KEY,user);

                    // 重定向到/plateform.html
                    log.debug("根据cookie还原用户登录状态,user={}",user);
                    response.sendRedirect("/plateform.html");
                    return false;
                }
            }

        }

        log.debug("没有免登录需要的cookie，进入登录页面");
        return true;
    }
}
